import { Fragment, useRef, useEffect, useState } from 'react';
import * as echarts from 'echarts/core';
import { GridComponent, LegendComponent } from 'echarts/components';
import { BarChart } from 'echarts/charts';
import { SVGRenderer } from 'echarts/renderers';
import { http } from '@/utils/http';

export default function HomeBarChart() {

  const [newsList, setNewsList] = useState({})  // 已发布新闻列表

  // 获取已发布新闻列表
  const getNewsList = async () => {
    const { data } = await http.get('/news?publishState=2&_expand=category')
    const sum = (function (data) {
      let sum = {}
      for (let i = 0; i < data.length; i++) {
        if (sum[data[i].category.title]) {
          sum[data[i].category.title] += 1
        } else {
          sum[data[i].category.title] = 1
        }
      }
      return sum
    })(data)
    // console.log('sum', sum)
    setNewsList(sum)
  }

  useEffect(() => {
    getNewsList()
  }, [])

  const domRef = useRef(null);
  useEffect(() => {
    echarts.use([GridComponent, BarChart, SVGRenderer, LegendComponent]);

    let myChart = echarts.getInstanceByDom(domRef.current); //有的话就获取已有echarts实例的DOM节点。
    if (myChart == null) { // 如果不存在，就进行初始化。
      myChart = echarts.init(domRef.current, null, {
        renderer: 'svg'
      });
    }
    var option;

    option = {
      xAxis: {
        type: 'category',
        data: Object.keys(newsList),
        axisLabel: {
          rotate: '30',  // x轴的标签旋转30度
          interval: 0  // 设置为0，强制显示所有x轴的标签，不会因为缩放而不显示
        }
      },
      yAxis: {
        type: 'value',
        minInterval: 1  // y轴最小刻度为1
      },
      legend: {
        data: ['新闻分类']
      },
      series: [
        {
          name: '新闻分类',
          data: Object.values(newsList),
          type: 'bar',
          showBackground: true,
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.2)'
          }
        }
      ]
    };
    option && myChart.setOption(option);
    // 窗口大小改变，调用eCharts实例的resize方法
    window.onresize = () => {
      myChart.resize()
    }
    return () => {
      // componentWillUnmount  组件卸载前设onresize为空
      window.onresize = null;
    }
  }, [newsList])

  return (
    <Fragment>
      <div ref={domRef} style={{ height: '300px', maxWidth: '130vh' }} />
    </Fragment>
  )
}